package com.hk.aefz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.aefz.mapper.EssayMapper;
import com.hk.aefz.po.*;
import com.hk.aefz.service.*;
import com.hk.aefz.utils.DateUtils;
import com.hk.aefz.utils.HtmlUtil;
import com.hk.aefz.vo.PageResult;
import com.hk.aefz.vo.PublishBlog;
import com.hk.aefz.vo.ResultMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author 阿尔法哲
 * @since 2020-07-21
 */
@Service
public class EssayServiceImpl extends ServiceImpl<EssayMapper, Essay> implements EssayService {

    @Autowired
    private EssayMapper essayMapper;

    @Autowired
    private CommentService commentService;

//    点赞
    @Autowired
    private PraiseService praiseService;
//收藏
    @Autowired
    private CollectService collectService;

    //分类
    @Autowired
    private SpecialService specialService;

    //标签
    @Autowired
    private LabelService labelService;

    @ApiOperation("博客发布")
    @Override
    @Transactional
    public ResultMsg saveBlog(PublishBlog publishBlog) {
        ResultMsg resultMsg = new ResultMsg();
//        1、进行封装
        Essay essay = new Essay();
        essay.setEtitle(publishBlog.getEtitle());
        essay.setEessay(publishBlog.getEessay());
        essay.setEstate(publishBlog.getEstate());
        essay.setEstatus(publishBlog.getEstatus());
        essay.setAid(publishBlog.getAid());
        System.out.println();
//        博客发布
        essayMapper.insert(essay);
//        博客对标签、网站分类、个人分类的绑定
        Map<String,Object> essayClassify = new HashMap<>();
        essayClassify.put("eid",essay.getEid());
        essayClassify.put("cid",publishBlog.getCid());
//        优化标签id存储
        String bid = publishBlog.getBid().toString();
        Pattern pattern = Pattern.compile("[\\[\\]\\s]");//截取中括号
        Matcher matcher = pattern.matcher(bid);
        String bids = matcher.replaceAll("");
        essayClassify.put("bid",bids);
        essayClassify.put("sid",publishBlog.getSid());
        essayClassify.put("gmtCreate",new DateUtils().dateString());
        essayClassify.put("gmtModified",new DateUtils().dateString());
        essayMapper.insertEssayClassify(essayClassify);
        resultMsg.setState(201);
        resultMsg.setMsg("发布成功!");
        return resultMsg;
    }

    @ApiOperation("分页查询当前账户未回收文章")
    @Override
    public PageResult<Essay> selectList(Integer page, Integer size, int dedid) {
        PageResult<Essay> result = new PageResult<>();
        Page<Essay> page1 = new Page<>(page,size);
        //        获取认证的账户id
        final int aid = (int) SecurityUtils.getSubject().getSession().getAttribute("aid");
        QueryWrapper<Essay> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("aid",aid)
                .eq("dedid",dedid)
                .orderByAsc("eid"); //升序
        Page<Essay> specialPage = essayMapper.selectPage(page1, queryWrapper);
        long total = specialPage.getTotal();
        long pages = 0l;
        if (total != 0l) {
            pages = total/size;
            if (total % size == 0) {
                pages = pages;
            }else {
                pages = pages+1;
            }
        }
        result.setObjects(specialPage.getRecords());
        result.setTotal(total);
        result.setSize(specialPage.getSize());
        result.setPages(pages);
        result.setCurrent(specialPage.getCurrent());
        return result;
    }

    @ApiOperation("分页查询公开/私有文章")
    @Override
    public PageResult<Essay> selectOpenList(Integer page, Integer size, Integer status) {
        PageResult<Essay> result = new PageResult<>();
        Page<Essay> page1 = new Page<>(page,size);
        //        获取认证的账户id
        final int aid = (int) SecurityUtils.getSubject().getSession().getAttribute("aid");
        QueryWrapper<Essay> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("aid",aid)
                .eq("dedid",0)
                .eq("estatus",status)
                .orderByAsc("eid"); //升序
        Page<Essay> specialPage = essayMapper.selectPage(page1, queryWrapper);
        long total = specialPage.getTotal();
        long pages = 0l;
        if (total != 0l) {
            pages = total/size;
            if (total % size == 0) {
                pages = pages;
            }else {
                pages = pages+1;
            }
        }
        result.setObjects(specialPage.getRecords());
        result.setTotal(total);
        result.setSize(specialPage.getSize());
        result.setPages(pages);
        result.setCurrent(specialPage.getCurrent());
        return result;
    }

    @ApiOperation("通过博客id查询博客详情")
    @Override
    public PageResult<Essay> selectById(Integer eid) {
        PageResult<Essay> pageResult = new PageResult<>();
        List<Essay> essays = new ArrayList<>();
        Essay essay = essayMapper.selectById(eid);
        essays.add(essay);
//        根据id查询当前博客评论量
        int count0 = commentService.count(eid);
        essay.setEComment(count0);
//        根据id查询当前博客的点赞
        QueryWrapper<Praise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("eid",eid);
        int count = praiseService.count(queryWrapper);
        essay.setEPraiseStati(count);
//        博客收藏量
        QueryWrapper<Collect> queryWrapper1 = new QueryWrapper<>();
        queryWrapper.eq("eid",eid);
        int count1 = collectService.count(queryWrapper1);
        essay.setECollect(count1);
//        获取分类名称及标签集合 0:个人分类id 1:名称 2：标签id集合
        Special special = specialService.selectByEid(eid);
        essay.setSpecial(special);
//        获取标签集合,进行转化赋值
        String bid = special.getBid();
        String[] split = bid.split("[,|]+");
        List<Integer> bids = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            bids.add(Integer.parseInt(split[i]));
        }
        List<Label> labels = labelService.listByIds(bids);
        essay.setLables(labels);
//        阅读量+1
        Integer eReadStatis = essay.getEReadStatis();
//        修改set
        Essay essay1 = new Essay();
        essay1.setEid(eid);
        essay1.setEReadStatis(eReadStatis+1);
        essayMapper.updateById(essay1);
        pageResult.setObjects(essays);
        return pageResult;
    }

    @ApiOperation("逻辑删除，放入回收站")
    @Override
    public ResultMsg delEssay(Integer eid, Integer dedid) {
        ResultMsg resultMsg = new ResultMsg();
        Essay essay = new Essay();
        essay.setDedid(dedid);
//        条件构造器
        final int ded = dedid == 1 ? 0 :1;
        QueryWrapper<Essay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("eid",eid)
                .eq("dedid",ded);
        int num = essayMapper.update(essay,queryWrapper);
        if (num == 1 && dedid == 1) {
            resultMsg.setState(200);
            resultMsg.setMsg("已放入回收站!");
        } else if (num == 1 && dedid == 0) {
            resultMsg.setState(200);
            resultMsg.setMsg("已恢复!");
        }else {
            resultMsg.setState(501);
            resultMsg.setMsg("请求异常，稍后重试");
        }
        return resultMsg;
    }

    @ApiOperation("主页查询,根据条件升序分页查询")
    @Override
    public PageResult<Essay> selectBlog(Integer cid,Integer page,Integer size) {
        PageResult<Essay> result = new PageResult<>();
        Page<Essay> page1 = new Page<>(page,size); //创建分页
//        创建条件构造器
        QueryWrapper<Essay> queryWrapper = new QueryWrapper<>();
//        获取当前日期的往前一周的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH,-7);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String gmtDate = format.format(calendar.getTime());
        String gmtModified = format.format(new Date());//当前日期
        if (cid == -2) { // 为你推荐
            System.out.println("为你推荐");
            queryWrapper
                    .eq("dedid",0) // 未删除
                    .eq("estatus",0) //公开
                    .between("gmt_modified",gmtDate,gmtModified)
                    .orderByAsc("eid"); //升序
        } else if (cid == -1) {
            System.out.println("近期热门");
            queryWrapper
                    .eq("dedid",0) // 未删除
                    .eq("estatus",0) //公开
                    .between("gmt_modified",gmtDate,gmtModified)
                    .orderByAsc("eid"); //升序

        } else if (cid == 0) {
            System.out.println("最新内容");
            queryWrapper
                    .eq("dedid",0) // 未删除
                    .eq("estatus",0) //公开
                    .between("gmt_modified",gmtDate,gmtModified)
                    .orderByAsc("eid"); //升序
        } else {
            System.out.println("根据网站分类id"+cid+"查询当前博客");
            queryWrapper
                    .eq("dedid",0) // 未删除
                    .eq("estatus",0) //公开
                    .between("gmt_modified",gmtDate,gmtModified)
                    .orderByAsc("eid"); //升序
        }
        Page<Essay> specialPage = essayMapper.selectPage(page1, queryWrapper);
//        获取所有查询到的数据，遍历取出html 标签
        List<Essay> essays = specialPage.getRecords();
        for (int i = 0; i < essays.size(); i++) {
            String eessay = essays.get(i).getEessay();
            String text = HtmlUtil.htmlRemoveTag(eessay);
            essays.get(i).setEessay(text);
        }
//        计算当前数据的总页数
        long total = specialPage.getTotal();
        long pages = 0l;
        if (total != 0l) {
            pages = total/size;
            if (total % size == 0) {
                pages = pages;
            }else {
                pages = pages+1;
            }
        }
        result.setObjects(essays);
        result.setTotal(total);
        result.setSize(specialPage.getSize());
        result.setPages(pages);
        result.setCurrent(specialPage.getCurrent());
        return result;
    }





}
